#!/usr/bin/env python
# -*- coding: utf8 -*-

from qtpy import QtWidgets, QtGui, QtCore
from qtpy import QtNetwork, QtCore
import getpass
import sys
# import sys
# if sys.version.startswith('3.'):
#     from .ui import resources_rc3
# else:
#     from .ui import resources_rc2

class QSingleton(QtCore.QObject):
    def __init__(self, cls):
        self.__cls = cls
        self.__app = None
        self.__server_name = 'SMART:{}:{}'.format(self.__cls.__name__, getpass.getuser())
        
    def __call__(self, *args, **kwargs):
        if self.__init_server():
            if args and kwargs:
                self.__app = self.__cls(*args, **kwargs)
            elif args:
                self.__app = self.__cls(*args)
            elif kwargs:
                self.__app = self.__cls(**kwargs)
            else:
                self.__app = self.__cls()
            return self.__app
        sys.exit()
        
    def __init_server(self):
        # 启动一个进程server
        # 检查是否有进程存在，如果没有则启动一个server
        if not self.__is_server_run(self.__server_name):
            self.__server = QtNetwork.QLocalServer() 
            QtNetwork.QLocalServer.removeServer(self.__server_name)
            self.__server.listen(self.__server_name)  
            # 监听连接：如果有连接说明有重复开启应用的操作，拒绝开启新应用并将旧应用唤醒
            self.__server.newConnection.connect(self.__new_connection)
            return True 
            
    def __new_connection(self, *args):
        if self.__app:
            self.__app.show_normal()
            
    def __is_server_run(self, servername):  
        # 尝试连接进程server
        # 如果连接上了说明有一个进程server存在，返回True，并关闭本次连接
        # 如果没连上说明系统还没有开启server，返回False
        ls = QtNetwork.QLocalSocket()
        ls.connectToServer(servername)
        if ls.waitForConnected(1000): 
            ls.disconnectFromServer()
            ls.close()
            return True 


@QSingleton
class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
    def __init__(self, app):
        QtWidgets.QSystemTrayIcon.__init__(self)
        self.app = app
        # icon = QtGui.QIcon(":/icons/smart_logo.png")
        # self.setIcon(icon)
        self.setToolTip("SMART")

        self.create_context_menu()
        self.activated.connect(self.on_activated)
        
    def set_tool_tip(self, text):
        self.setToolTip(text)

    def set_icon(self, path):
        icon = QtGui.QIcon(path)
        self.setIcon(icon)

    def on_activated(self, reason):
        # QtWidgets.QSystemTrayIcon.Trigger    单击
        # QtWidgets.QSystemTrayIcon.DoubleClick  双击

        # QtWidgets.QSystemTrayIcon.Context    右键
        if reason != QtWidgets.QSystemTrayIcon.Context:
            self.app.show()
    
    def show_win(self):
        self.show()
        self.app.show()

    def on_mini_action_triggered(self, *arg):
        self.current_widget.hide()
        
    def on_restore_action_triggered(self, *arg):
        self.current_widget.showNormal()
        
    def create_context_menu(self):
        # create actions
        self.minimizeAction = QtWidgets.QAction(u"最小化", self, triggered=self.on_mini_action_triggered)
        self.restoreAction = QtWidgets.QAction(u"还原", self, triggered=self.on_restore_action_triggered)
        self.quitAction = QtWidgets.QAction(u"退出", self, triggered=QtWidgets.QApplication.quit)
        # create menu
        self.trayIconMenu = QtWidgets.QMenu()
        self.trayIconMenu.addAction(self.minimizeAction)
        self.trayIconMenu.addAction(self.restoreAction)
        self.trayIconMenu.addSeparator()
        self.trayIconMenu.addAction(self.quitAction)
        # set context menu
        self.setContextMenu(self.trayIconMenu)